home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!netnews
- From: a1s@ix.netcom.com (Andrew Snyder)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: Fri, 19 Jan 1996 22:33:52 GMT
- Organization: Netcom
- Message-ID: <4dorr8$i58@cloner3.netcom.com>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
- NNTP-Posting-Host: ix-har6-12.ix.netcom.com
- X-NETCOM-Date: Fri Jan 19 11:36:08 AM PST 1996
- X-Newsreader: Forte Free Agent 1.0.82
-
- Bill Simpson <wsimpson@uwinnipeg.ca> wrote:
-
- >Is there a fast way to decide whether a number n is a power of 2?
-
- >In my problem
- >if ((high-low+1) is a power of 2)
- > {
- > do one thing
- > }
- >else
- > {
- > do another
- > }
- >e.g. low=0, high=7: 7-0+1 is a power of 2.
-
- >The only thing I have thought of is that if n is power of 2
- >log(n)/log(2) is an integer
- >BUT this is going to be a SLOW computation. Needs to be fast.
-
- >Since I am dealing with unsigned long ints, I guess I can just store all
- >31 powers of 2 in a table and compare to n. Though I don't know a fast
- >algorithm to compare a number to 31 numbers in an array.
-
- >Perhaps there is a tricky nonportable way to see if I have power-of-2 by
- >looking at bits? (That is fine for this application)
-
- >Thanks very much for any help.
-
- >Bill Simpson
-
- no tricks
-
- #define ISPOW2(x) (((x) & 1) ^ 1)
-
-
- Andrew Snyder
- a1s@ix.netcom.com
- char disclaimer[] = {'\0'}; /* I'm on cash net */
-
-